package com.lingkang.flychat.ws;


import io.netty.bootstrap.ServerBootstrap;
import io.netty.channel.ChannelFuture;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.nio.NioServerSocketChannel;
import org.springframework.stereotype.Component;

@Component
public final class NettyServer {


    public void NettyServer(int port) throws Exception {
        System.out.println("运行netty");
        //创建 主线程组，主线程接收并把任务丢给从线程，从线程做处理
        EventLoopGroup mainGrorp = new NioEventLoopGroup();
        //从线程组
        EventLoopGroup subGrorp = new NioEventLoopGroup();
        // netty服务器创建，ServerBootstrap是一个启动类
        ServerBootstrap serverBootstrap = new ServerBootstrap();
        serverBootstrap.group(mainGrorp, subGrorp)      //设置主从线程
                .channel(NioServerSocketChannel.class)   //  设置nio的双向管道
                .childHandler(new NettyServerInitializer());   // 子处理器
        try {
            //启动server并绑定端口监听和设置同步方式
            ChannelFuture channelFuture = serverBootstrap.bind(port).sync();
            //关闭监听方式
            channelFuture.channel().closeFuture().sync();
        } catch (Exception e) {
            System.err.println("netty服务器启动异常。。。。" + e.getMessage());
        } finally {
            mainGrorp.shutdownGracefully();
            subGrorp.shutdownGracefully();
        }
    }
}
